package com.liang.exam.interceptors;


import com.liang.exam.entity.Student;
import com.liang.exam.service.StudentService;
import com.liang.exam.utils.TokenValidator;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import com.liang.exam.utils.JwtUtil;
import com.liang.exam.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenValidator tokenValidator;

    @Autowired
    private StudentService studentService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //令牌验证
        String token = request.getHeader("Authorization");
        //验证token
        try {
            tokenValidator.validateToken(token);
            Map<String, Object> claims = JwtUtil.parseToken(token);
            //把业务数据存储到ThreadLocal中
            ThreadLocalUtil.set(claims);

            String role = (String) claims.get("role");
            int StudentId =(int) claims.get("id");
            String requestURI = request.getRequestURI();
            String ipAddress = request.getRemoteAddr();

            //防止拿token去其他电脑登录
            if(role.equals("student")) {
                Student studentBinding = studentService.findById(StudentId);
                if (!studentBinding.getIpAddress().equals(ipAddress)) {
                    response.setStatus(403);
                    return false;
                }
            }

            if (role.equals("0")) { // 教师角色，只能访问 /teacher 路径
                if (!requestURI.startsWith("/teacher")) {
                    response.setStatus(403);
                    return false;
                }
            } else if (role.equals("student")) { // 学生角色，只能访问 /student 路径
                if (!requestURI.startsWith("/student")) {
                    response.setStatus(403);
                    return false;
                }
            } else if (role.equals("1")) { // 管理员角色，可以访问 /admin 和 /teacher 路径
                if (!requestURI.startsWith("/admin") && !requestURI.startsWith("/teacher")) {
                    response.setStatus(403);
                    return false;
                }
            }

            return true;
        } catch (Exception e) {
            //http响应状态码为401
            response.setStatus(401);
            //不放行
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocal中的数据
        ThreadLocalUtil.remove();
    }
}
